"""笔记管理模块的视图

基于前端业务需求重构的API视图。
完全匹配前端接口需求和新的模型结构。
"""

from rest_framework import status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from django.db.models import Q
from django.db import transaction
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.shortcuts import get_object_or_404
from django.http import Http404
from datetime import datetime

from .models import Folder, Note, ShareLink
from .serializers import (
    FolderSerializer,
    NoteSerializer,
    ShareLinkSerializer,
    SyncDataSerializer,
    SyncResponseSerializer,
    FolderCreateSerializer,
    NoteCreateSerializer,
    NoteUpdateSerializer,
    SharedContentSerializer
)


class FolderViewSet(ModelViewSet):
    """文件夹视图集
    
    提供文件夹的CRUD操作，完全匹配前端需求。
    """
    
    serializer_class = FolderSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """获取当前用户的文件夹"""
        return Folder.objects.filter(created_by=self.request.user).order_by('isDefault', 'sortOrder', 'name')
    
    def get_serializer_class(self):
        """根据动作返回对应的序列化器"""
        if self.action == 'create':
            return FolderCreateSerializer
        return FolderSerializer
    
    def create(self, request, *args, **kwargs):
        """创建文件夹
        
        自动创建默认文件夹（如果不存在）。
        """
        # 确保用户有默认文件夹
        self._ensure_default_folders(request.user)
        
        return super().create(request, *args, **kwargs)
    
    def list(self, request, *args, **kwargs):
        """获取文件夹列表
        
        确保返回包含默认文件夹的完整列表。
        """
        # 确保用户有默认文件夹
        self._ensure_default_folders(request.user)
        
        return super().list(request, *args, **kwargs)
    
    def destroy(self, request, *args, **kwargs):
        """删除文件夹
        
        不允许删除默认文件夹。
        """
        folder = self.get_object()
        
        if folder.isDefault:
            return Response(
                {'error': '不能删除默认文件夹'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 将该文件夹下的笔记移动到"未分类笔记"
        uncategorized_folder = Folder.objects.filter(
            name='未分类笔记',
            created_by=request.user,
            isDefault=True
        ).first()
        
        if uncategorized_folder:
            Note.objects.filter(folderId=folder.id, author=request.user).update(
                folderId=uncategorized_folder.id
            )
        
        return super().destroy(request, *args, **kwargs)
    
    @action(detail=True, methods=['post'])
    def share(self, request, pk=None):
        """创建文件夹共享链接"""
        folder = self.get_object()
        
        # 创建共享链接
        share_data = {
            'resourceType': 'folder',
            'resourceId': folder.id,
            'password': request.data.get('password'),
            'expiresAt': request.data.get('expiresAt')
        }
        
        serializer = ShareLinkSerializer(data=share_data, context={'request': request})
        if serializer.is_valid():
            share_link = serializer.save()
            
            # 更新文件夹的共享状态
            folder.isShared = True
            folder.shareLink = share_link.shareLink
            folder.sharePassword = share_link.password
            folder.save()
            
            return Response(FolderSerializer(folder, context={'request': request}).data)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['post'])
    def batch_update_order(self, request):
        """批量更新文件夹排序
        
        接收格式：
        {
            "folders": [
                {"id": 1, "sortOrder": 1},
                {"id": 2, "sortOrder": 2}
            ]
        }
        """
        folders_data = request.data.get('folders', [])
        
        if not folders_data:
            return Response(
                {'error': '没有提供文件夹数据'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        updated_folders = []
        
        try:
            with transaction.atomic():
                for folder_data in folders_data:
                    folder_id = folder_data.get('id')
                    sort_order = folder_data.get('sortOrder')
                    
                    if not folder_id or sort_order is None:
                        continue
                    
                    # 确保文件夹属于当前用户
                    folder = Folder.objects.filter(
                        id=folder_id,
                        created_by=request.user
                    ).first()
                    
                    if folder and not folder.isDefault:
                        folder.sortOrder = sort_order
                        folder.save(update_fields=['sortOrder'])
                        updated_folders.append(folder)
                
                return Response({
                    'message': f'成功更新 {len(updated_folders)} 个文件夹的排序',
                    'updated_count': len(updated_folders)
                })
                
        except Exception as e:
            return Response(
                {'error': f'批量更新失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=True, methods=['delete'])
    def unshare(self, request, pk=None):
        """取消文件夹共享"""
        folder = self.get_object()
        
        # 删除共享链接
        ShareLink.objects.filter(
            resourceType='folder',
            resourceId=folder.id,
            created_by=request.user
        ).delete()
        
        # 更新文件夹状态
        folder.isShared = False
        folder.shareLink = None
        folder.sharePassword = None
        folder.save()
        
        return Response({'message': '已取消共享'}, status=status.HTTP_200_OK)
    
    def _ensure_default_folders(self, user):
        """确保用户有默认文件夹
        
        创建"全部笔记"和"未分类笔记"默认文件夹。
        """
        # 创建"全部笔记"文件夹
        Folder.objects.get_or_create(
            name='全部笔记',
            created_by=user,
            defaults={
                'isDefault': True,
                'count': 0
            }
        )
        
        # 创建"未分类笔记"文件夹
        Folder.objects.get_or_create(
            name='未分类笔记',
            created_by=user,
            defaults={
                'isDefault': True,
                'count': 0
            }
        )


class NoteViewSet(ModelViewSet):
    """笔记视图集
    
    提供笔记的CRUD操作，完全匹配前端需求。
    """
    
    serializer_class = NoteSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """获取当前用户的笔记
        
        支持按文件夹过滤。
        """
        queryset = Note.objects.filter(author=self.request.user).order_by('-id')
        
        # 按文件夹过滤
        folder_id = self.request.query_params.get('folderId')
        if folder_id:
            if folder_id == '1':  # 全部笔记
                pass  # 返回所有笔记
            elif folder_id == '2':  # 未分类笔记
                queryset = queryset.filter(folderId=2)
            else:
                queryset = queryset.filter(folderId=folder_id)
        
        # 搜索功能
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) | Q(content__icontains=search)
            )
        
        return queryset
    
    def get_serializer_class(self):
        """根据动作返回对应的序列化器"""
        if self.action == 'create':
            return NoteCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return NoteUpdateSerializer
        return NoteSerializer
    
    def create(self, request, *args, **kwargs):
        """创建笔记
        
        如果没有指定文件夹，默认放到"未分类笔记"。
        """
        data = request.data.copy()
        
        # 如果没有指定文件夹，使用"未分类笔记"
        if 'folderId' not in data or not data['folderId']:
            data['folderId'] = 2
        
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        note = serializer.save()
        
        # 更新文件夹计数
        self._update_folder_counts(request.user)
        
        return Response(
            NoteSerializer(note, context={'request': request}).data,
            status=status.HTTP_201_CREATED
        )
    
    def update(self, request, *args, **kwargs):
        """更新笔记"""
        response = super().update(request, *args, **kwargs)
        
        # 更新文件夹计数
        self._update_folder_counts(request.user)
        
        return response
    
    def destroy(self, request, *args, **kwargs):
        """删除笔记"""
        response = super().destroy(request, *args, **kwargs)
        
        # 更新文件夹计数
        self._update_folder_counts(request.user)
        
        return response
    
    @action(detail=True, methods=['post'])
    def share(self, request, pk=None):
        """创建笔记共享链接"""
        note = self.get_object()
        
        # 创建共享链接
        share_data = {
            'resourceType': 'note',
            'resourceId': note.id,
            'password': request.data.get('password'),
            'expiresAt': request.data.get('expiresAt')
        }
        
        serializer = ShareLinkSerializer(data=share_data, context={'request': request})
        if serializer.is_valid():
            share_link = serializer.save()
            
            # 更新笔记的共享状态
            note.isShared = True
            note.shareLink = share_link.shareLink
            note.sharePassword = share_link.password
            note.save()
            
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['delete'])
    def unshare(self, request, pk=None):
        """取消笔记共享"""
        note = self.get_object()
        
        # 删除共享链接
        ShareLink.objects.filter(
            resourceType='note',
            resourceId=note.id,
            created_by=request.user
        ).delete()
        
        # 更新笔记状态
        note.isShared = False
        note.shareLink = None
        note.sharePassword = None
        note.save()
        
        return Response({'message': '已取消共享'}, status=status.HTTP_200_OK)
    
    @action(detail=False, methods=['post'])
    def search(self, request):
        """搜索笔记"""
        query = request.data.get('query', '')
        folder_id = request.data.get('folderId')
        
        queryset = self.get_queryset()
        
        if query:
            queryset = queryset.filter(
                Q(title__icontains=query) | Q(content__icontains=query)
            )
        
        if folder_id and folder_id != '1':  # 不是"全部笔记"
            queryset = queryset.filter(folderId=folder_id)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    def _update_folder_counts(self, user):
        """更新用户所有文件夹的笔记数量"""
        folders = Folder.objects.filter(created_by=user)
        for folder in folders:
            folder.update_count()


class ShareLinkViewSet(ModelViewSet):
    """共享链接视图集
    
    管理共享链接的创建、查看和删除。
    """
    
    serializer_class = ShareLinkSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """获取当前用户的共享链接"""
        return ShareLink.objects.filter(created_by=self.request.user).order_by('-createdAt')


class SharedContentView(APIView):
    """共享内容访问视图
    
    允许匿名用户通过共享链接访问内容。
    """
    
    permission_classes = [permissions.AllowAny]
    
    def post(self, request, share_id):
        """获取共享内容
        
        支持密码保护的共享内容。
        """
        try:
            share_link = ShareLink.objects.get(shareId=share_id)
        except ShareLink.DoesNotExist:
            return Response(
                {'error': '共享链接不存在或已过期'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 检查是否过期
        if share_link.is_expired():
            return Response(
                {'error': '共享链接已过期'},
                status=status.HTTP_410_GONE
            )
        
        # 检查密码
        if share_link.password:
            provided_password = request.data.get('password')
            if not provided_password or provided_password != share_link.password:
                return Response(
                    {'error': '密码错误'},
                    status=status.HTTP_401_UNAUTHORIZED
                )
        
        # 增加访问次数
        share_link.increment_access_count()
        
        # 获取共享内容
        if share_link.resourceType == 'folder':
            try:
                folder = Folder.objects.get(id=share_link.resourceId)
                notes = Note.objects.filter(folderId=folder.id, author=folder.created_by)
                
                content_data = {
                    'resourceType': 'folder',
                    'resourceId': folder.id,
                    'title': folder.name,
                    'author': folder.created_by.username,
                    'createdAt': folder.createdAt.strftime('%Y年%m月%d日 %H:%M') if hasattr(folder.createdAt, 'strftime') else str(folder.createdAt),
                    'updatedAt': folder.updatedAt.strftime('%Y年%m月%d日 %H:%M') if hasattr(folder.updatedAt, 'strftime') else str(folder.updatedAt),
                    'notes': [
                        {
                            'id': note.id,
                            'title': note.title,
                            'content': note.content,
                            'createdAt': note.createdAt,
                            'updatedAt': note.updatedAt
                        }
                        for note in notes
                    ]
                }
            except Folder.DoesNotExist:
                return Response(
                    {'error': '共享的文件夹不存在'},
                    status=status.HTTP_404_NOT_FOUND
                )
        
        elif share_link.resourceType == 'note':
            try:
                note = Note.objects.get(id=share_link.resourceId)
                
                content_data = {
                    'resourceType': 'note',
                    'resourceId': note.id,
                    'title': note.title,
                    'content': note.content,
                    'author': note.author.username,
                    'createdAt': note.createdAt,
                    'updatedAt': note.updatedAt
                }
            except Note.DoesNotExist:
                return Response(
                    {'error': '共享的笔记不存在'},
                    status=status.HTTP_404_NOT_FOUND
                )
        
        else:
            return Response(
                {'error': '不支持的共享类型'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        serializer = SharedContentSerializer(content_data)
        return Response(serializer.data)


# 同步相关代码已删除，改为直接使用CRUD接口
